package com.hospital.wx.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.hospital.wx.common.CommonResult;
import com.hospital.wx.controller.form.LoginOrRegisterForm;
import com.hospital.wx.controller.form.UpdatePatientUserForm;
import com.hospital.wx.exception.WxErrorCode;
import com.hospital.wx.service.PatientUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/patient/user")
@Tag(name = "PatientUserController", description = "患者登录注册管理接口")
@Slf4j
public class PatientUserController {

    @Autowired
    private PatientUserService patientUserService;

    @PostMapping("/loginOrRegister")
    @Operation(summary = "患者登录或注册")
    @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
    public CommonResult loginOrRegister(@RequestBody @Valid LoginOrRegisterForm form) {
        try {
            // 调用服务层方法
            Map<String, Object> map = patientUserService.loginOrRegister(
                    form.getCode(), form.getNickname(), form.getPhoto(), form.getSex());
            String msg = MapUtil.getStr(map, "msg");

            Integer id = MapUtil.getInt(map, "id");
            // 判断是否成功
            if (msg == null || id == null) {
                // 返回失败响应，使用枚举管理错误信息
                return CommonResult.failed(WxErrorCode.LOGIN_OR_REGISTER_FAILED);
            }
            // 生成 token 信息
            StpUtil.login(id);
            String token = StpUtil.getTokenValue();
            // 返回用户填写的信息和 token 信息
            return CommonResult.ok(map).put(CommonResult.RETURN_TOKEN, token);
        } catch (Exception e) {
            // 记录异常日志
            log.error("登录或注册过程中发生异常", e);
            // 返回通用错误响应，给前端提示
            return CommonResult.failed(WxErrorCode.LOGIN_OR_REGISTER_FAILED);
        }
    }

    @PostMapping("/uploadAvatar")
    @Operation(summary = "更新头像")
    @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
    public CommonResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        log.info("接收到文件上传请求");
        log.info("文件名: {}", file.getOriginalFilename());
        log.info("文件大小: {}", file.getSize());
        log.info("文件类型: {}", file.getContentType());
        log.info("文件是否为空: {}", file.isEmpty());

        try {
            String filename = patientUserService.uploadAvatar(file);
            return CommonResult.ok().put("result", filename);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return CommonResult.error("文件上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    @Operation(summary = "更新用户信息")
    @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
    public CommonResult update(@RequestBody @Valid UpdatePatientUserForm form) {
        Map<String, Object> map = BeanUtil.beanToMap(form);
        int rows = patientUserService.updatePatientUser(map);
        if (rows == 1) {
            return CommonResult.ok().put("msg", "更新成功");
        } else {
            return CommonResult.failed("更新失败");
        }
    }

    @GetMapping("/selectAppointmentCount")
    @Operation(summary = "查询待完成的预约个数")
    @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
    public CommonResult selectAppointmentCount() {
        try {
            int count = patientUserService.selectAppointmentCount();
            return CommonResult.ok().put(CommonResult.RETURN_RESULT, count);
        } catch (Exception e) {
            log.error("查询过程中出现错误", e);
            return CommonResult.failed("查询过程中出现错误");
        }
    }
}
